package com.syxbyi._3tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;

public class ChatServerThread implements Runnable {

    private final Map<Socket, User> clients;
    private final Socket socket;

    ChatServerThread(ChatServer server, Socket socket) {
        clients = server.clients;
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String info = bufferedReader.readLine();
            // 客户端发来的第一条信息表示用户信息
            User user = new User(info);
            clients.put(socket, user);       // 记录在线用户
            System.out.printf("[%d号技师] 用户%s上线\n", Thread.currentThread().getId(), user.getName());
            while(true) {
                // 收到消息打印在服务器端，并且转发给所有在线客户端
                String msg = bufferedReader.readLine();
                if (Command.isGoodbyeCommand(msg)) {
                    System.out.printf("[%d号技师] 用户%s下线\n", Thread.currentThread().getId(), user.getName());
                    clients.remove(socket);
                    break;
                }
                if (msg != null) {
                    System.out.printf("[%d号技师] {User=%s, Message=%s}\n", Thread.currentThread().getId(), user.getName(), msg);
                    // 转发给除了当前用户的其他人
                    for (Socket s: clients.keySet()) {
                        if (!s.equals(socket)) {
                            System.out.printf("[%d号技师] {User=%s, Message=%s} -> {User=%s}\n",
                                    Thread.currentThread().getId(), user.getName(), msg, clients.get(s).getName());
                            PrintStream printStream = new PrintStream(s.getOutputStream());
                            printStream.println("[" + user.getName() + "] " + msg);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
